package model;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class ClassArtifact extends JavaArtifact{

	public static final int MAGIC_NUMBER = 0xCAFEBABE;
	
	protected ClassArtifact(String path) {
		super(path, JavaFileExtension.CLASS);
	}
	
	@Override
	public ClassVersion calculateClassVersion() {
		FileInputStream inputStream = null;
		try {
			File file = new File(super.getPath());
			inputStream = new FileInputStream(file);
			ClassVersion classVersion = calculateClassVersion(inputStream);
			setClassVersion(classVersion);
			return classVersion;
		} catch (FileNotFoundException e) {
			throw new InvalidJavaArtifactContentException("File not found:"+e.getMessage());
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public ClassVersion calculateClassVersion(InputStream inputStream) {
		try {
			
			DataInputStream data = new DataInputStream(inputStream);
			
			int magicNumber = data.readInt();
			if (MAGIC_NUMBER != magicNumber) {
				String hex = Integer.toHexString(magicNumber);
				throw new InvalidJavaArtifactContentException("Class has invalid header[" + hex + "]");
			}

			int minor = data.readUnsignedShort();
			int major = data.readUnsignedShort();
			ClassVersion classVersion = new ClassVersion(minor, major);
			setClassVersion(classVersion);
			
			return classVersion;
		} catch (IOException e) {
			throw new InvalidJavaArtifactContentException("IO exception occured: " + e.getMessage());
		}
	}
	
	public static void main(String[] args) {
		ClassArtifact artifact = new ClassArtifact("C:\\Users\\ttoacargil\\Desktop\\SoapMessage.class");
		artifact.calculateClassVersion();
	}
	
}
